/**
 * Author: 冯亮亮
 * Remark: 采购计划
 */
lyfdefine(['echarts', 'time-line-month'], function (echarts) {
    return ({
            data: function () {
                return {
                    tableData: [],
                    dataList: [],
                    loading: false,
                    ifShow: false,
                    lastGmvTargetList: [],
                    dialogVisible: false,
                    value1: '',
                    infor: {},
                    updateFrom: [],
                    pickerOptions: {
                        shortcuts: [{
                            text: '最近一个月',
                            onClick(picker) {
                                let start = new Date();
                                start.setMonth(start.getMonth() - 1);
                                start.setDate(1);
                                const end = new Date();
                                let oneDay = 3600 * 1000 * 24
                                end.setDate(1)
                                end.setTime(end.getTime() - oneDay)
                                picker.$emit('pick', [start, end]);
                            }
                        }, {
                            text: '最近三个月',
                            onClick(picker) {
                                let start = new Date();
                                start.setMonth(start.getMonth() - 3);
                                start.setDate(1);
                                const end = new Date();
                                let oneDay = 3600 * 1000 * 24
                                end.setDate(1)
                                end.setTime(end.getTime() - oneDay)
                                picker.$emit('pick', [start, end]);
                            }
                        }]
                    },
                    charts: false,
                    cType: false,
                    checked: false,
                    a: '',
                    templateType: '',
                    dialogVisible1: false,
                    dialogVisible3: false,
                    titleText: '导入引导',
                    activeStep: 1,
                    cancelBtnText: '取消',
                    fileList: [],
                    importErrInfo: '',//导入校验失败信息
                    dateList: [],
                    tables: [],
                    festivals: [],
                    weekDate: [],
                    needMergeArr: ['channel'], // 有合并项的列
                    rowMergeArrs: {},
                    pageIndex: 1,
                    pageSize: 50,
                    totalPage: 0,
                    totalCount: 0,
                    dataForm: {
                        startTime: '',
                        endTime: '',
                        quota1: [],
                        dateRange:'',
                        allChannelCode: 'A0000'
                    },
                    dataFormEChart: {
                        startTime: '',
                        endTime: '',
                        allChannelCode: 'A0000',
                        // areaCodeList:[],
                        // channelCodeList:[],
                        // saleOrgCodeList:[]
                    },
                    dataListLoading: false,
                    warehouseOptions: [],
                    supplierOptions: [],
                    // salesOrganizationCodeList: [],
                    targetOption: [
                        {
                            label: '目标销售额',
                            value: 1
                        }, {
                            label: '实际销售额',
                            value: 2
                        }, {
                            label: '销售额达成率',
                            value: 3
                        }, {
                            label: '销售额达成差值',
                            value: 7
                        }, {
                            label: '目标毛利额',
                            value: 4
                        }, {
                            label: '实际毛利额',
                            value: 5
                        }, {
                            label: '毛利额达成率',
                            value: 6
                        }, {
                            label: '毛利额达成差值',
                            value: 8
                        }
                    ],
                    currentPage4: '',
                    value2: ['目标销售额', '实际销售额', '实际毛利额', '目标毛利额'],
                    labels: [],
                    exportForm: {
                        pageNum: '',
                        pageSize: '',
                        rowParamList: []
                    },
                    dateRange:''
                }
            },
            mounted() {
                //初始化开始月和结束月
                this.dataForm.startTime = this.getBeginDate()
                this.dataForm.endTime = this.getEndDate()
                this.getDataList();
                this.$nextTick(function () {
                    this.initEcharts();
                });
                // this.getHolidays();
            },
            methods: {
                getHolidays() {
                    this.$http({
                        url: 'scm-plan-admin/api/v1/outService/dateLabels',
                        method: 'get',
                        params: {
                            "startDate": this.getBeginOflastMonth()
                        }
                    }).then(result => {
                        this.festivals = result.data.data

                    })
                },
                //此日期为当前月往前推第十四月
                getBeginDate() {
                    let date = new Date();
                    date.setMonth(date.getMonth() - 13);
                    date.setDate(1);
                    let y = date.getFullYear(); //年
                    let m = date.getMonth() + 1; //月
                    let d = date.getDate(); //日
                    return y + "-" + m + "-" + d;
                },
                //此日期为当前月
                getEndDate() {
                    let date = new Date();
                    date.setDate(1);
                    let y = date.getFullYear(); //年
                    let m = date.getMonth() + 1; //月
                    let d = date.getDate(); //日
                    return y + "-" + m + "-" + d + ' 00:00:00';
                },
                getDataList() {
                    this.dataListLoading = true;
                    this.dataForm.pageSize = this.pageSize;
                    this.dataForm.pageNum = this.pageIndex;
                    this.$http({
                        url: "/scm-plan-admin/api/v1/gmvTarget/list",
                        method: 'post',
                        data: this.dataForm
                    }).then(result => {
                        const data = result.data;
                        if (data && data.code === '0') {
                            this.weekDate = data.data.dateList;
                            let list = data.data.infoList;
                            if (list == null) {
                                this.dataList = [];
                                this.totalCount = 0;
                            } else {
                                this.handerDataList(list);
                                this.rowMergeArrs = this.rowMergeHandle(this.needMergeArr, this.dataList); // 处理合并数据
                                this.totalCount = data.data.total;
                            }
                        } else {
                            this.$message.error(result.data.msg);
                            this.dataList = [];
                            this.totalPage = 0;
                        }
                        this.dataListLoading = false;
                    }).catch(() => {
                        this.dataListLoading = false;
                    })
                },
                rowMergeHandle(arr, data) {
                    if (!Array.isArray(arr) && !arr.length) return false;
                    if (!Array.isArray(data) && !data.length) return false;
                    let needMerge = {};
                    arr.forEach(i => {
                        needMerge[i] = {
                            rowArr: [],
                            rowMergeNum: 0
                        };
                        data.forEach((item, index) => {
                            if (index === 0) {
                                needMerge[i].rowArr.push(1);
                                needMerge[i].rowMergeNum = 0;
                            } else {
                                if (item[i] === data[index - 1][i]) {
                                    needMerge[i].rowArr[needMerge[i].rowMergeNum] += 1;
                                    needMerge[i].rowArr.push(0);
                                } else {
                                    needMerge[i].rowArr.push(1);
                                    needMerge[i].rowMergeNum = index;
                                }
                            }
                        });
                    });
                    return needMerge;
                },
                mergeAction(val, rowIndex, colData) {
                    let _row = this.rowMergeArrs[val].rowArr[rowIndex];
                    let _col = _row > 0 ? 1 : 0;
                    return [_row, _col];
                },
                arraySpanMethod({row, column, rowIndex, columnIndex}) {
                    // 没办法循环判断具体是那一列 所以就只好写了多个if
                    // if (column.property === 'channel') return this.mergeAction('skuName', rowIndex, column);
                    // if (column.property === 'area') return this.mergeAction('skuName', rowIndex, column);
                    // if (columnIndex === 0) return this.mergeAction('skuName', rowIndex, column);
                    if (columnIndex === 0 || column.property === 'channel' || column.property === 'area' || column.property === 'salesOrganization' || column.property === 'category') {
                        if (this.isContain(this.dataForm.quota1, 0) && rowIndex % this.targetOption.length === 0) {
                            return {
                                rowspan: this.targetOption.length,
                                colspan: 1
                            }
                        } else if (this.isContain(this.dataForm.quota1, 0) && rowIndex % this.targetOption.length !== 0) {
                            return {
                                rowspan: 0,
                                colspan: 0
                            }
                        }
                        if (!this.isContain(this.dataForm.quota1, 0) && rowIndex % this.dataForm.quota1.length === 0) {
                            return {
                                rowspan: this.dataForm.quota1.length,
                                colspan: 1
                            }
                        } else if (!this.isContain(this.dataForm.quota1, 0) && rowIndex % this.dataForm.quota1.length !== 0) {
                            return {
                                rowspan: 0,
                                colspan: 0
                            }
                        }
                    }
                },
                isContain(list, item) {
                    if (list.length === 0) {
                        return true
                    }
                    let e = list.find(e => {
                        return e === item
                    })
                    if (e !== undefined) {
                        return true
                    } else {
                        return false
                    }
                },
                handerDataList(dataList) {
                    let newDataList = [];
                    let _this = this
                    _this.lastGmvTargetList = []
                    dataList.forEach((item, index, array) => {
                        let confirmQty = []
                        this.infor.area = item.area
                        this.infor.salesOrganization = item.salesOrganization
                        this.infor.category = item.category
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 1)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.gmvTargetLabel, // 目标GMV指标名称
                                qtyList: item.gmvTarget,            // 目标GMV指标数量
                                flag: index,
                                idList: item.idList,
                                type: 2,
                            });
                            let gmvTargetList = []
                            gmvTargetList.push(...item.gmvTarget)
                            _this.lastGmvTargetList.push(gmvTargetList)
                        }
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 2)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.gmvRealTargetLabel, // 实际GMV指标名称
                                qtyList: item.gmvRealTarget,            // 实际GMV指标数量
                                flag: index,
                            });
                        }
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 3)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.gmvTargetAcRateLabel, // GMV达成率指标名称
                                qtyList: item.gmvTargetAcRate,            // GMV达成率指标数量
                                flag: index,
                                type: 1,
                            });
                        }
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 7)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.gmvTargetDifferenceLabel, // GMV达成率指标名称
                                qtyList: item.gmvTargetDifference,            // GMV达成率指标数量
                                flag: index,
                            });
                        }
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 4)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.groProTargetLabel, // 目标毛利额指标名称
                                qtyList: item.groProTarget,            // 目标毛利额指标数量
                                flag: index,
                            });
                        }
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 5)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.groProRealTargetLabel, // 实际毛利额指标名称
                                qtyList: item.groProRealTarget,            // 实际毛利额指标数量
                                flag: index,
                            });
                        }

                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 6)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.groProAcRateLabel, // 毛利额达成率指标名称
                                qtyList: item.groProAcRate,            // 毛利额达成率指标数量
                                flag: index,
                                type: 1,
                            });
                        }
                        if (_this.isContain(_this.dataForm.quota1, 0) || _this.isContain(_this.dataForm.quota1, 8)) {
                            newDataList.push({
                                channel: item.channel,
                                salesOrganization: item.salesOrganization,
                                area: item.area,
                                category: item.category,
                                planConfirmLabel: item.groProDifferenceLabel, // 毛利额达成率指标名称
                                qtyList: item.groProDifference,            // 毛利额达成率指标数量
                                flag: index,

                            });
                        }
                    });
                    this.dataList = newDataList
                },
                initEcharts(boo) {
                    // 基于准备好的dom，初始化echarts实例
                    let _this = this
                    _this.loading = true
                    if (boo) {
                        _this.dataFormEChart.startTime = boo[0];
                        _this.dataFormEChart.endTime = boo[1];
                    } else {
                        _this.dataFormEChart.startTime = this.dataForm.startTime;
                        _this.dataFormEChart.endTime = this.dataForm.endTime;
                    }
                    this.$http({
                        url: '/scm-plan-admin/api/v1/gmvTarget/listAll',
                        method: 'post',
                        data: _this.dataFormEChart
                    }).then(result => {

                        if (result.data.code === '0') {
                            _this.dateList = result.data.data.dateList
                            _this.labels = [];
                            if (result.data.data.infoList) {
                                result.data.data.infoList.forEach(e => {

                                    _this.labels.push(e.gmvTargetLabel);
                                    _this.labels.push(e.gmvRealTargetLabel);
                                    _this.labels.push(e.gmvTargetAcRateLabel);
                                    _this.labels.push(e.gmvTargetDifferenceLabel);
                                    _this.labels.push(e.groProTargetLabel);
                                    _this.labels.push(e.groProRealTargetLabel);
                                    _this.labels.push(e.groProAcRateLabel);
                                    _this.labels.push(e.groProDifferenceLabel);

                                    _this.gmvTarget = e.gmvTarget
                                    _this.gmvRealTarget = e.gmvRealTarget
                                    _this.gmvTargetAcRate = this.acFormat(e.gmvTargetAcRate)
                                    _this.gmvTargetDifference = e.gmvTargetDifference
                                    _this.groProTarget = e.groProTarget
                                    _this.groProRealTarget = e.groProRealTarget
                                    _this.groProAcRate = this.acFormat(e.groProAcRate)
                                    _this.groProDifference = e.groProDifference
                                })
                            }
                            _this.initOpentionEcharts()
                        } else {
                            _this.$message.error(result.data.msg);
                        }
                        _this.loading = false
                    }).then(e => {
                        _this.loading = false
                    })

                },
                acFormat(val) {
                    let acFormatQty = []
                    val.forEach(e => {
                        acFormatQty.push((e * 100).toFixed(3));
                    })
                    return acFormatQty
                },
                initOpentionEcharts() {
                    let _this = this
                    let ec = null;
                    if (echarts != undefined) {
                        ec = echarts;
                    } else {
                        ec = window.echarts;
                    }
                    var myChart = ec.init(document.getElementById('echarts'));
                    let arr = {}
                    let serArr = [

                        {
                            name: '目标销售额',
                            type: 'bar',
                            data: _this.gmvTarget
                        },
                        {
                            name: '实际销售额',
                            type: 'bar',
                            data: _this.gmvRealTarget
                        },
                        {
                            name: '目标毛利额',
                            type: 'bar',
                            data: _this.groProTarget
                        },
                        {
                            name: '实际毛利额',
                            type: 'bar',
                            data: _this.groProRealTarget
                        },
                        {
                            name: '销售额达成率',
                            yAxisIndex: 1,
                            type: 'line',
                            data: _this.gmvTargetAcRate
                        },
                        {
                            name: '销售额达成差值',
                            type: 'bar',
                            data: _this.gmvTargetDifference
                        },
                        {
                            name: '毛利额达成率',
                            yAxisIndex: 1,
                            type: 'line',
                            data: _this.groProAcRate
                        },
                        {
                            name: '毛利额达成差值',
                            type: 'bar',
                            data: _this.groProDifference
                        }
                    ]
                    let arr2 = []
                    serArr.forEach(e => {
                        let obj = _this.value2.find(e1 => {
                            return e1 === e.name
                        })
                        if (obj) {
                            arr2.push(e)
                        }
                    })
                    let option = {
                        color: ['#4BA2FD', '#5AD8A6', '#6DC8EC', '#945FB9'],
                        title: {
                            text: ''
                        },
                        dataZoom: [
                            {
                                type: 'slider',//有单独的滑动条，用户在滑动条上进行缩放或漫游。inside是直接可以是在内部拖动显示
                                show: true,//是否显示 组件。如果设置为 false，不会显示，但是数据过滤的功能还存在。
                                start: 0,//数据窗口范围的起始百分比0-100
                                end: 50,//数据窗口范围的结束百分比0-100
                                bottom: -10 //距离底部的距离
                            },
                            //2.在内部可以横向拖动
                            {
                                type: 'inside',// 内置于坐标系中
                                start: 0,
                                end: 50
                            }
                        ],
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'cross',
                                crossStyle: {
                                    color: '#999'
                                }
                            }
                        },
                        legend: {
                            type: 'scroll',
                            orient: 'horizontal',
                            data: _this.value2,
                            selected: arr
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: _this.dateList,
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        yAxis: [
                            {
                                type: 'value',
                                name: '量',
                                axisLabel: {
                                    formatter: '{value}'
                                }
                            },
                            {
                                type: 'value',
                                name: '百分比',
                                axisLabel: {
                                    formatter: '{value} %'
                                },
                                splitLine: {     //去掉网格线
                                    show: false
                                }
                            }
                        ],
                        series: arr2
                    };
                    myChart.setOption(option, true);
                },
                offsetFun(val) {
                    let offSetNum = val.target.vueComponent.offSetNum
                    let obj = {
                        startTime: '',
                        endTime: ''
                    }
                    if (offSetNum === 16) {
                        obj.startTime = this.dateFormat('YYYY-mm-dd HH:MM:SS', val.target.vueComponent.dateList[val.target.vueComponent.offSetNum - 1].date),
                            obj.endTime = this.dateFormat('YYYY-mm-dd HH:MM:SS', val.target.vueComponent.dateList[val.target.vueComponent.offSetNum].date1)
                    } else {
                        obj.startTime = this.dateFormat('YYYY-mm-dd HH:MM:SS', val.target.vueComponent.dateList[val.target.vueComponent.offSetNum - 1].date)
                        obj.endTime = this.dateFormat('YYYY-mm-dd HH:MM:SS', val.target.vueComponent.dateList[val.target.vueComponent.offSetNum + 1].date)
                    }
                    this.dataForm.startTime = obj.startTime
                    this.dataList = []
                    this.pageIndex = 1
                    this.getDataList()
                },
                changePicker(val) {
                    this.initEcharts(val)
                },

                searchList() {
                    let _this = this
                    _this.dataList = []
                    _this.pageIndex = 1
                    if(_this.dataForm.dateRange){
                        _this.dataForm.startTime = Date.parse(_this.dataForm.dateRange[0])
                        _this.dataForm.endTime = Date.parse(_this.dataForm.dateRange[1])
                    }
                    this.dataForm.quota1 = this.dataForm.quota11
                    _this.getDataList()
                    _this.dialogVisible = false
                },
                clearCondition() {
                    this.dataForm.quota11 = []
                    this.dataForm.dateRange = ''
                    this.dataForm.startTime = this.getBeginDate()
                    this.dataForm.endTime = this.getEndDate()
                },
                sizeChangeHandle(val) {
                    this.pageSize = val;
                    this.pageIndex = 1;
                    this.getDataList();
                },
                currentChangeHandle(val) {
                    this.pageIndex = val;
                    this.getDataList();
                },
                fullScreen() {
                    let _this = this
                    let selection = _this.$refs.table.selection
                    let rows = []
                    selection.forEach(item => {
                        rows.push(item)
                    })
                    _this.dialogVisible1 = true
                    //赋值全屏table
                    _this.$nextTick(function () {
                        this.$refs.tablemax.clearSelection();
                        if (rows) {
                            rows.forEach(row => {
                                _this.$refs.tablemax.toggleRowSelection(row, true);
                            });
                        }
                    });
                },
                leaveFullScreen() {
                    let _this = this
                    _this.dialogVisible1 = false
                    let selection = _this.$refs.tablemax.selection
                    let rows = []
                    selection.forEach(item => {
                        rows.push(item)
                    })
                    //赋值全屏table
                    this.$refs.table.clearSelection();
                    if (rows) {
                        rows.forEach(row => {
                            _this.$refs.table.toggleRowSelection(row, true);
                        });
                    }
                },
                //上传文件
                submitUpload() {
                    let that = this;
                    const loading = this.$loading({
                        lock: true,
                        text: '上传中···   ',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    const config = {headers: {'Content-Type': 'multipart/form-data'}}
                    let uploadData = new FormData()
                    uploadData.append("file", this.fileList[0].raw)
                    this.$http.post('scm-plan-admin/api/v1/gmvTarget/importVerification?type=' + this.templateType, uploadData, config
                    ).then(function (res) {
                        const data = res.data;
                        if (data && data.code === '0') {
                            that.$message.success('上传成功')
                            that.activeStep = 3;
                            loading.close();
                        } else {
                            that.$message.error('上传失败')
                            that.importErrInfo = data.msg;
                            that.activeStep = 2;
                            loading.close();
                        }
                        loading.close();
                    }).catch(e => {
                        that.$message.error('上传失败')
                        that.importErrInfo = e;
                        that.activeStep = 2;
                        loading.close();
                    });
                },
                onClickCancelBtn() {
                    this.fileList = [];
                    this.activeStep = 1;
                    this.dialogVisible3 = false;
                    this.importErrInfo = '';
                },
                handleCommand(command) {
                    this.templateType = command;
                    this.dialogVisible3 = true;
                },
                //初始化上传接口参数
                handleChangeUpload(file) {
                    var FileExt = file.name.replace(/.+\./, "");
                    if (['xls', 'xlsx'].indexOf(FileExt.toLowerCase()) === -1) {
                        this.importErrInfo = '非excel文件';
                    }
                    this.fileList.push(file)
                    this.activeStep = 2;
                },
                //关闭上传框
                handleClose(done) {
                    this.$confirm('确认关闭？')
                        .then(_ => {
                            this.fileList = [];
                            this.activeStep = 1;
                            this.dialogVisible3 = false;
                            this.importErrInfo = '';
                            done();
                        })
                        .catch(_ => {
                        });
                },
                //模板下载
                downLodeTemplate() {
                    let that = this;
                    that.dataListLoading = true;
                    let url = '/scm-plan-admin/api/v1/gmvTarget/downLoadTemplate/' + this.templateType;
                    window.location.href = url;
                },
                exportExcel(val) {
                    let _this = this
                    this.exportForm.allChannelCode = this.dataForm.allChannelCode
                    // this.exportForm.unitType = this.dataForm.unitType
                    //分页信息
                    this.exportForm.pageSize = this.pageSize;
                    this.exportForm.pageNum = this.pageIndex;
                    //复选框下标集合
                    this.exportForm.rowIndex = []
                    //起始日期
                    this.exportForm.startTime = this.dataForm.startTime
                    let boo = false
                    if (val === 2) {
                        if (this.dialogVisible1) {
                            if (this.$refs.tablemax.selection && this.$refs.tablemax.selection.length > 0) {
                                this.$refs.tablemax.selection.forEach(e => {
                                    this.exportForm.rowIndex.push(e.flag)
                                })
                            } else {
                                boo = true
                            }
                        } else {
                            if (this.$refs.table.selection && this.$refs.table.selection.length > 0) {
                                this.$refs.table.selection.forEach(e => {
                                    this.exportForm.rowIndex.push(e.flag)
                                })
                            } else {
                                boo = true
                            }
                        }
                    }
                    if (boo) {
                        this.$message({
                            message: '请选择至少一条数据',
                            type: 'error'
                        })
                        return false
                    }
                    const loading = this.$loading({
                        lock: true,
                        text: '下载中···   ',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    this.$http({
                        url: '/scm-plan-admin/api/v1/gmvTarget/exportExcel',
                        method: 'post',
                        responseType: 'blob',
                        data: this.exportForm,
                        params: {type: val}
                    }).then(result => {
                        let data = result.data;
                        let fileReader = new FileReader();
                        fileReader.onload = function () {
                            try {
                                let jsonData = JSON.parse(this.result);  // 说明是普通对象数据，后台转换失败
                                loading.close();
                                if (jsonData.msg) {
                                    _this.$message({
                                        message: jsonData.msg,
                                        type: 'error'
                                    })
                                }
                            } catch (err) {   // 解析成对象失败，说明是正常的文件流
                                const disposition = result.headers['content-disposition'];
                                let fileName = disposition.substring(disposition.indexOf('filename=') + 9, disposition.length);
                                fileName = decodeURIComponent(fileName);
                                let blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
                                if ('download' in document.createElement('a')) { // 非IE下载
                                    const elink = document.createElement('a')
                                    elink.download = fileName
                                    elink.style.display = 'none'
                                    elink.href = URL.createObjectURL(blob)
                                    document.body.appendChild(elink)
                                    elink.click()
                                    URL.revokeObjectURL(elink.href) // 释放URL 对象
                                    document.body.removeChild(elink)
                                } else { // IE10+下载
                                    navigator.msSaveBlob(blob, fileName)
                                }
                                loading.close();
                            }
                        };
                        fileReader.readAsText(data, "utf-8")
                    }).catch(function (e) {
                        loading.close();
                    })
                },
                download(data) {
                    if (!data) {
                        return
                    }
                    let url = window.URL.createObjectURL(new Blob([data]))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', 'excel.xlsx')

                    document.body.appendChild(link)
                    link.click()
                },
                labelChange(val) {
                    this.initOpentionEcharts()
                },
                dateFormat(fmt, date) {

                    let ret;
                    const opt = {
                        "Y+": date.getFullYear().toString(),        // 年
                        "m+": (date.getMonth() + 1).toString(),     // 月
                        "d+": date.getDate().toString(),            // 日
                        "H+": date.getHours().toString(),           // 时
                        "M+": date.getMinutes().toString(),         // 分
                        "S+": date.getSeconds().toString()          // 秒
                        // 有其他格式化字符需求可以继续添加，必须转化成字符串
                    };
                    for (let k in opt) {
                        ret = new RegExp("(" + k + ")").exec(fmt);
                        if (ret) {
                            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                        }
                    }
                    return fmt;
                },
                findStyle({row, column, rowIndex, columnIndex}) {
                    if (column.label && typeof parseInt(column.label.substr(0, 1)) === 'number' && !isNaN(column.label.substr(0, 1))) {
                        return "padding: 0;background: #4ba2fd;color: #ffffff"
                    } else {
                        return "padding: 0;background: #f8f8f8"
                    }
                },
                saveButton() {
                    this.dataListLoading = true;
                    let set = []
                    let data = this.updateFrom;
                    let ifTrue = false;
                    if (this.dialogVisible1) {
                        if (this.$refs.tablemax.selection && this.$refs.tablemax.selection.length) {
                            ifTrue = true;
                        }
                    } else {
                        if (this.$refs.table.selection && this.$refs.table.selection.length) {
                            ifTrue = true;
                        }
                    }
                    if (ifTrue) {
                        data.forEach((e, i) => {
                            e.idList.forEach((a, j) => {
                                if (e.qtyList[j] && e.qtyList[j] !== this.lastGmvTargetList[i][j]) {
                                    let formData = {};
                                    formData.idList = a;
                                    formData.gmvTarget = e.qtyList[j];
                                    set.push(formData);
                                }
                            })
                        })
                    } else {
                        this.$message({
                            message: '未选择数据或未修改数据',
                            type: 'error'
                        })
                        this.dataListLoading = false;
                        return false
                    }
                    console.log(set)
                    this.$http({
                        url: '/scm-plan-admin/api/v1/gmvTarget/updateTarget?unitType=' + this.dataForm.unitType,
                        method: 'post',
                        data: set
                    }).then(result => {
                        const data = result.data;
                        if (data && data.code === '0') {
                            this.$message.success("保存成功");
                        } else {
                            this.$message.error(result.data.msg);
                        }
                        this.getDataList();
                        this.dataListLoading = false;
                    }).catch(() => {
                        this.dataListLoading = false;
                    })
                },
                selectChange(selection) {
                    this.updateFrom = [];
                    if (selection && selection.length) {
                        selection.forEach(e => {
                            this.dataList.forEach(a => {
                                if (e.flag === a.flag && a.planConfirmLabel === this.labels[0]) {
                                    this.updateFrom.push(a);
                                }
                            })
                        })
                    } else {
                        this.updateFrom = [];
                    }
                },
                selectAllChange(selection) {
                    this.updateFrom = [];
                    if (selection && selection.length) {
                        selection.forEach((e, idx) => {
                            if (e.flag === this.dataList[idx].flag && this.dataList[idx].planConfirmLabel === this.labels[0]) {
                                this.updateFrom.push(this.dataList[idx]);
                            }
                        })
                    } else {
                        this.updateFrom = [];
                    }
                }
            },
            template: `
    <div>
                <el-card class="box-card">
              <div slot="header" class="clearfix">
                <div style="text-align: right;margin: 5px">
                <span style="float: left;color: rgba(0,0,0,0.85);font-size: 16px;line-height:35px">销售额历史目标</span>
                <el-button size="small" style="float: left;margin-left: 10px"  @click="fullScreen" >全屏</el-button>
                 <el-popover
                    placement="bottom"
                    title="高级搜索"
                    width="100%"
                    trigger="click">
                    <div>   
                 <el-row>
                 <el-form :inline="true" :model="dataForm" class="demo-form-inline">
                  <el-form-item label="起止日期:">
                    <el-date-picker
                                  v-model="dataForm.dateRange"
                                  type="daterange"
                                  range-separator="至"
                                  start-placeholder="开始日期"
                                  end-placeholder="结束日期">
                                </el-date-picker>
</el-form-item>
                      <el-form-item label="指标:">
                             <el-select  style="width:100%" v-model="dataForm.quota11" clearable  multiple  placeholder="请选择">
                              <el-option
                                v-for="item in targetOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                              </el-option>
                            </el-select>
                      </el-form-item>
                    </el-form>
                </el-row>
                <div style="text-align: center">
                    <span class="dialog-footer">
                    <el-button size="mini" @click="clearCondition">清 除 条 件</el-button>
                    <el-button type="primary" size="mini" @click="searchList">搜 索</el-button>
                  </span>
                </div>
           </div>
                    <el-button slot="reference" size="small" icon="el-icon-search" type="primary" style="float: right;margin-left: 10px">高级搜索</el-button>
                  </el-popover>
<!--               <el-button  size="small" @click="saveButton" type="primary" style="margin-right: 5px;">保存</el-button>-->

<!--                <el-dropdown @command="handleCommand">-->
<!--                  <el-button size="small" type="primary" style="margin-right: 5px;">-->
<!--                    导入<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                  </el-button>-->
<!--                  <el-dropdown-menu slot="dropdown">-->
<!--                    <el-dropdown-item command="1">直营/加盟渠道数据导入</el-dropdown-item>-->
<!--                    <el-dropdown-item command="2">APP/经销中心/云商渠道数据导入</el-dropdown-item>-->
<!--                  </el-dropdown-menu>-->
<!--                </el-dropdown>-->

                 <el-dropdown @command="exportExcel">
                      <el-button size="small" type="primary" >
                        导出<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="1">当前页数据</el-dropdown-item>
                        <el-dropdown-item :command="2">已勾选数据</el-dropdown-item>
                        <el-dropdown-item :command="3">所有查询结果</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                
             </div>
              </div>
                <el-dialog :title="titleText" :visible.sync="dialogVisible3" :close-on-click-modal="false" :beforeClose="handleClose" width="700px">
                    <el-steps :active="activeStep" align-center>
                        <el-step title="上传文档"></el-step>
                        <el-step title="导入并校验"></el-step>
                        <el-step title="创建完成"></el-step>
                    </el-steps>
                    <div v-show="activeStep !== 3">
                        1.<el-button type="text">点击<a href="javascript:void(0)" @click="downLodeTemplate" style="color:#17b3a3;">下载导入数据模板</a></el-button>将要导入的数据填充到数据导入模板文件中。
                        <div>
                            <div style="color:red;">注意事项:</div>
                            <p>（1）模板中的标题不可更改，标题行不可删除；</p>
                            <p>（2）除必填的列以外，不需要的列可以删除；</p>
                            <p>（3）单次导入的数据不超过10000条；</p>
                        </div>
                    </div>
                    <div v-show="activeStep === 1">
                        2. 请选择要导入的数据文件。
                        <el-upload :on-change="handleChangeUpload" accept=".xls,.xlsx" :show-file-list="false" :auto-upload="false" class="upload-demo" style="padding:5px 18px;" action="https://jsonplaceholder.typicode.com/posts/" :limit="1" :file-list="fileList">
                            <el-button size="small" type="primary"><i class="el-icon-plus"></i>&nbsp;选择文件</el-button>
                            <div slot="tip" class="el-upload__tip" style="color:#ccc;">请选择excel文件，允许上传附件类型（xls,xlsx），文件大小不得大于100MB</div>
                        </el-upload>
                    </div>
                    <div class="file-list" v-show="fileList.length > 0">
                        <div class="file-list__item" style="marginTop:20px;padding:10px 20px;backgroundColor: #eaeaea;display:flex;justifyContent: space-between;" v-for="item in fileList" :key="item.name">
                            <div>{{item.name}}</div>
                            <div>{{item.size | formatFileSize}}KB</div>
                            <div>完成</div>
                        </div>
                    </div>
                    <div slot="footer" class="dialog-footer" style="text-align:center;">
                        <el-button type="primary" @click.native="submitUpload" :disabled="activeStep===1" v-show="activeStep !==3">开始导入</el-button>
                        <el-button @click.native="onClickCancelBtn" v-show="activeStep !==3">{{cancelBtnText}}</el-button>
                        <el-button @click.native="onClickCancelBtn" v-show="activeStep ===3">关闭</el-button>
                    </div>
                    <p style="text-align: center;color:red;margin-top:10px;" v-if="activeStep === 2 && (importErrInfo != '' && importErrInfo != null)">{{importErrInfo}}</p>
                </el-dialog>

<!--            <time-line-month ref="timeLine" @offsetFun="offsetFun"></time-line-month>-->
            <el-table v-loading="dataListLoading" v-if="dataList.length === 0 "></el-table>
            <el-table
                :data="dataList"
                :span-method="arraySpanMethod"
                center
                ref="table"
                v-loading="dataListLoading"
                v-show="dataList.length"
                border
                highlight-current-rows
                height="33vh"
                @select="selectChange"
                @select-all="selectAllChange"
                :header-row-style="{height: '20px',fontSize: '14px', fontWeight: '700',lineHeight: '36px',textAlign: 'center',backgroundColor: '#f3f4f4',padding: 0}"
                :row-style="{ color: '#999A9A', height: '16px',fontSize: '12px', fontWeight: 400,lineHeight: '26px',textAlign: 'center'}"
                :cell-style="{padding: 0}"
                :header-cell-style="findStyle"
                style="width: 100%;padding: 0"
                :highlight-current-row="false">
            <el-table-column
                    type="selection"
                     fixed="left"
                    width="55">
            </el-table-column>
            <el-table-column
            width="130"
                  prop="channel"
                  fixed="left"
                  label="渠道" align="left">
                  <template slot-scope="scope">
                      {{scope.row.channel === null || scope.row.channel === '' ? '全渠道' : scope.row.channel}}
                    </template>
                </el-table-column>
                <el-table-column
                v-if="infor.area"
                width="130"
                  prop="area"
                  fixed="left"
                  label="区域" align="left">
                </el-table-column>
                <el-table-column
                v-if="infor.category"
                  prop="category"
                  width="130"
                  fixed="left"
                  label="品类" align="left">
                </el-table-column>
                <el-table-column
                v-if="infor.salesOrganization"
                  prop="salesOrganization"
                  width="200"
                  fixed="left"
                  label="销售组织（公司）" align="left">
                </el-table-column>
                <el-table-column
                width="130"
                fixed="left"
                  prop="planConfirmLabel" label="指标" align="left">
                </el-table-column>
            <el-table-column
                v-for="(week, index) in weekDate"
              :label="week" width="120" align="right">
              <template slot-scope="scope">
                  <span>{{scope.row.qtyList[index] == 0? '-' : ((scope.row.planConfirmLabel == '销售额达成率' || scope.row.planConfirmLabel == '毛利额达成率')?(scope.row.qtyList[index]*100).toFixed(3):scope.row.qtyList[index].toFixed(3)) }}<span v-if="scope.row.qtyList[index] != 0 && (scope.row.planConfirmLabel == '销售额达成率' || scope.row.planConfirmLabel == '毛利额达成率')">%</span></span>
              </template>
            </el-table-column>
        </el-table>
            <div style=";width: 100%;">
                <div style="height: 30px;width: 1px"></div>
                <el-row>
                 <span style="margin-left: 20px">日期范围</span>
                <el-date-picker
                  v-model="value1"
                  @change="changePicker"
                  type="daterange"
                  size="mini"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">  
                </el-date-picker>
                <el-select v-model="value2" size="mini" clearable collapse-tags :multiple-limit="4" multiple placeholder="请选择指标" @change="labelChange">
                    <el-option
                      v-for="item in labels"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                 <el-pagination
                 @size-change="sizeChangeHandle"
                 @current-change="currentChangeHandle"
                 :current-page="pageIndex"
                 :page-sizes="[10, 20, 30, 50]"
                 :page-size="pageSize"
                 :total="totalCount"
                 :page-count="totalPage"
                  small
                  style="float: right"
                  layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
                </el-row>
                <div v-loading="loading" style="margin-top: 20px;height: 30vh;width: 100%;" id="echarts"></div>
            </div>
            </el-card>
        <el-dialog
          center
          :style="{ padding: '0px' }"
          fullscreen
          :show-close="false"
          :visible.sync="dialogVisible1">
           <div style="">
          <div style="text-align: right;margin: 5px">
           <el-button size="small" style="float: left;margin-left: 10px" @click="leaveFullScreen">退出全屏</el-button>
           <el-popover
                    placement="bottom"
                    title="高级搜索"
                    width="100%"
                    trigger="click">
                    <div>   
                 <el-row>
                 <el-form :inline="true" :model="dataForm" class="demo-form-inline">
                  <el-form-item label="起止日期:">
                    <el-date-picker
                                  v-model="dataForm.dateRange"
                                  type="daterange"
                                  range-separator="至"
                                  start-placeholder="开始日期"
                                  end-placeholder="结束日期">
                                </el-date-picker>
</el-form-item>
                      <el-form-item label="指标:">
                             <el-select  style="width:100%" v-model="dataForm.quota11" clearable  multiple  placeholder="请选择">
                              <el-option
                                v-for="item in targetOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                              </el-option>
                            </el-select>
                      </el-form-item>
                    </el-form>
                </el-row>
                <div style="text-align: center">
                    <span class="dialog-footer">
                    <el-button size="mini" @click="clearCondition">清 除 条 件</el-button>
                    <el-button type="primary" size="mini" @click="searchList">搜 索</el-button>
                  </span>
                </div>
           </div>
                    <el-button slot="reference" size="small" icon="el-icon-search" type="primary" style="float: right;margin-left: 10px;margin-bottom: 10px">高级搜索</el-button>
                  </el-popover>
<!--                  <el-button  size="small" @click="saveButton" type="primary" style="margin-right: 5px;">保存</el-button>-->
<!--                       <el-dropdown @command="handleCommand">-->
<!--                  <el-button size="small" type="primary" style="margin-right: 5px;">-->
<!--                    导入<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                  </el-button>-->
<!--                  <el-dropdown-menu slot="dropdown">-->
<!--                    <el-dropdown-item command="1">直营/加盟渠道数据导入</el-dropdown-item>-->
<!--                    <el-dropdown-item command="2">APP/经销中心/云商渠道数据导入</el-dropdown-item>-->
<!--                  </el-dropdown-menu>-->
<!--                </el-dropdown>-->
                 <el-dropdown @command="exportExcel">
                      <el-button size="small" type="primary" >
                        导出<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="1">当前页数据</el-dropdown-item>
                        <el-dropdown-item :command="2">已勾选数据</el-dropdown-item>
                        <el-dropdown-item :command="3">所有查询结果</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    </div>
                    <el-table v-loading="dataListLoading" v-if="dataList.length === 0 "></el-table>
                <el-table
                :data="dataList"
                :span-method="arraySpanMethod"
                center
                v-loading="dataListLoading"
                ref="tablemax"
                border
                v-show="dataList.length"
                highlight-current-rows
                height="85vh"
                @select="selectChange"
                @select-all="selectAllChange"
                :header-row-style="{height: '20px',fontSize: '14px', fontWeight: '700',lineHeight: '36px',textAlign: 'center',backgroundColor: '#f3f4f4',padding: 0}"
                :row-style="{ color: '#999A9A', height: '16px',fontSize: '12px', fontWeight: 400,lineHeight: '26px',textAlign: 'center'}"
                :cell-style="{padding: 0}"
                  :header-cell-style="findStyle"
                style="width: 100%;padding: 0"
                :highlight-current-row="false">
            <el-table-column
                    type="selection"
                     fixed="left"
                    width="55">
            </el-table-column>
           <el-table-column
            width="130"
                  prop="channel"
                  fixed="left"
                  label="渠道" align="left">
                  <template slot-scope="scope">
                      {{scope.row.channel === null || scope.row.channel === '' ? '全渠道' : scope.row.channel}}
                    </template>
                </el-table-column>
                <el-table-column
                v-if="infor.area"
                width="130"
                  prop="area"
                  fixed="left"
                  label="区域" align="left">
                </el-table-column>
                <el-table-column
                v-if="infor.category"
                  prop="category"
                  width="130"
                  fixed="left"
                  label="品类" align="left">
                </el-table-column>
                <el-table-column
                v-if="infor.salesOrganization"
                  prop="salesOrganization"
                  width="200"
                  fixed="left"
                  label="销售组织（公司）" align="left">
                </el-table-column>
                 <el-table-column
                width="130"
                fixed="left"
                  prop="planConfirmLabel" label="指标" align="left">
                </el-table-column>
            <el-table-column
                v-for="(week, index) in weekDate"
              :label="week" width="120" align="right">
              <template slot-scope="scope">
                  <span>{{scope.row.qtyList[index] == 0? '-' : ((scope.row.planConfirmLabel == '销售额达成率' || scope.row.planConfirmLabel == '毛利额达成率')?(scope.row.qtyList[index]*100).toFixed(3):scope.row.qtyList[index].toFixed(3)) }}<span v-if="scope.row.qtyList[index] != 0 && (scope.row.planConfirmLabel == '销售额达成率' || scope.row.planConfirmLabel == '毛利额达成率')">%</span></span>
              </template>
            </el-table-column>
        </el-table>
          <el-pagination
                 @size-change="sizeChangeHandle"
                 @current-change="currentChangeHandle"
                 :current-page="pageIndex"
                 :page-sizes="[10, 20, 30, 50]"
                 :page-size="pageSize"
                 :total="totalCount"
                 :page-count="totalPage"
                  small
                  style="float: right"
                  layout="total, sizes, prev, pager, next, jumper">
                </el-pagination>
           </div>
          <span slot="footer" class="dialog-footer">
          </span>
        </el-dialog>

    </div>
    `
        }
    );
});